#!/bin/sh

#set -vx

LCFILE=/etc/pki/ca-trust/ca-legacy.conf
LLINK=/etc/pki/ca-trust/source/ca-bundle.legacy.crt
LDEFAULT=/usr/share/pki/ca-trust-legacy/ca-bundle.legacy.default.crt
LDISABLE=/usr/share/pki/ca-trust-legacy/ca-bundle.legacy.disable.crt

# 不存在的值或任何意外值都会被视为 “默认值”
is_disabled()
{
    grep -i "^legacy *= *disable *$" $LCFILE >/dev/null 2>&1
}

do_check()
{
    is_disabled
    if [ $? -eq 0 ]; then
        echo "遗留 CA 在文件 $LCFILE 中设置为 DISABLED（影响安装/升级）"
        LEXPECT=$LDISABLE
    else
        echo "遗留 CA 在文件 $LCFILE 中设置为 DEFAULT（影响安装/升级）"
        LEXPECT=$LDEFAULT
    fi
    echo "符号链接 $LLINK 的状态: "
    readlink -v $LLINK
}

do_install()
{
    is_disabled
    if [ $? -eq 0 ]; then
        # 已找到，遗留功能已禁用
        ln -sf $LDISABLE $LLINK
    else
        # 表达式未找到，遗留功能被设置为默认值
        ln -sf $LDEFAULT $LLINK
    fi
}

do_default()
{
    sed -i 's/^legacy *=.*$/legacy=default/' $LCFILE
    do_install
    /usr/bin/update-ca-trust
}

do_disable()
{
    sed -i 's/^legacy *=.*$/legacy=disable/' $LCFILE
    do_install
    /usr/bin/update-ca-trust
}

do_help()
{
    echo "用法: $0 [check | default | disable | install]"
}

if [[ $# -eq 0 ]]; then
  # 无参数
  do_help
  exit $?
fi

if [[ "$1" = "install" ]]; then
  do_install
  exit $?
fi

if [[ "$1" = "default" ]]; then
  do_default
  exit $?
fi
if [[ "$1" = "disable" ]]; then
  do_disable
  exit $?
fi

if [[ "$1" = "check" ]]; then
  do_check
  exit $?
fi

echo "$0: 不支持的命令 $1"
do_help
